package android.framework.widget.exittext;

import android.framework.R;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
 * 
 * @ClassName: DeleteButtonEditText
 * @Description: TODO
 * @author jtf19@163.com
 * @date 2013-7-23 上午11:04:09
 * 
 */
public class DeleteButtonEditText extends EditText {
	private TextWatcher mTextWatcher = new TextWatcher() {
		public void afterTextChanged(Editable paramEditable) {
			if (TextUtils.isEmpty(paramEditable))
				DeleteButtonEditText.this
						.setCompoundDrawablesWithIntrinsicBounds(null, null,
								null, null);
			else
				DeleteButtonEditText.this
						.setCompoundDrawablesWithIntrinsicBounds(
								null,
								null,
								DeleteButtonEditText.this
										.getResources()
										.getDrawable(
												R.drawable.search_del_button_selecter),
								null);
		}

		public void beforeTextChanged(CharSequence paramCharSequence,
				int paramInt1, int paramInt2, int paramInt3) {
		}

		public void onTextChanged(CharSequence paramCharSequence,
				int paramInt1, int paramInt2, int paramInt3) {
		}
	};

	private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
		public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
			switch (paramMotionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (((int) paramMotionEvent.getX() <= -60
						+ paramView.getWidth())
						|| (TextUtils.isEmpty(DeleteButtonEditText.this
								.getText())))
					return false;
				DeleteButtonEditText.this.setText("");
				int type = DeleteButtonEditText.this.getInputType();
				DeleteButtonEditText.this.setInputType(InputType.TYPE_NULL);
				DeleteButtonEditText.this.onTouchEvent(paramMotionEvent);
				DeleteButtonEditText.this.setInputType(type);
				break;
			}
			return false;
		}
	};

	public DeleteButtonEditText(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		init();
	}

	public DeleteButtonEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		init();
	}

	public DeleteButtonEditText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init();
	}

	private void init() {
		addTextChangedListener(this.mTextWatcher);
		setOnTouchListener(this.onTouchListener);
	}
}